Code coverage report for src/typeahead/typeahead.js

Statements: 84% (126 / 150)      Branches: 62.75% (64 / 102)      Functions: 86.67% (26 / 30)      Lines: 86.26% (113 / 131)      Ignored: none     

All files » src/typeahead/ » typeahead.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283    1       42                                     42   42   1   44     44   44 44 44   44 55 55   44   44           44 10 10       44 201         44 61 61           61       1     44 6     44 11 11   11 11 11 11   11         44 259       259     44 19 19 18 32   18 10     44           44                                             44 44 38     38 2 2 2         44 44 6 6 6   6 6 6     44       42 42               37   37           39 39 702       39 39 117       39     39 39 39   39 39 39 39 39     39     39   1 1   2 2 2           39   58 58       58       58 58 58   58 46   46         39   40 40       39   98 19 19 19 19 19       39 39 39 39              
'use strict';
 
angular.module('mgcrea.ngStrap.typeahead', ['mgcrea.ngStrap.tooltip', 'mgcrea.ngStrap.helpers.parseOptions'])
 
  .provider('$typeahead', function() {
 
    var defaults = this.defaults = {
      animation: 'am-fade',
      prefixClass: 'typeahead',
      prefixEvent: '$typeahead',
      placement: 'bottom-left',
      template: 'typeahead/typeahead.tpl.html',
      trigger: 'focus',
      container: false,
      keyboard: true,
      html: false,
      delay: 0,
      minLength: 1,
      filter: 'filter',
      limit: 6,
      autoSelect: false,
      comparator: '',
      trimValue: true
    };
 
    this.$get = function($window, $rootScope, $tooltip, $timeout) {
 
      var bodyEl = angular.element($window.document.body);
 
      function TypeaheadFactory(element, controller, config) {
 
        var $typeahead = {};
 
        // Common vars
        var options = angular.extend({}, defaults, config);
 
        $typeahead = $tooltip(element, options);
        var parentScope = config.scope;
        var scope = $typeahead.$scope;
 
        scope.$resetMatches = function(){
          scope.$matches = [];
          scope.$activeIndex = options.autoSelect ? 0 : -1; // If set to 0, the first match will be highlighted
        };
        scope.$resetMatches();
 
        scope.$activate = function(index) {
          scope.$$postDigest(function() {
            $typeahead.activate(index);
          });
        };
 
        scope.$select = function(index, evt) {
          scope.$$postDigest(function() {
            $typeahead.select(index);
          });
        };
 
        scope.$isVisible = function() {
          return $typeahead.$isVisible();
        };
 
        // Public methods
 
        $typeahead.update = function(matches) {
          scope.$matches = matches;
          Iif(scope.$activeIndex >= matches.length) {
            scope.$activeIndex = options.autoSelect ? 0: -1;
          }
 
          // When the placement is not one of the bottom placements, re-calc the positioning
          // so the results render correctly.
          if (/^(bottom|bottom-left|bottom-right)$/.test(options.placement)) return;
 
          // wrap in a $timeout so the results are updated
          // before repositioning
          $timeout($typeahead.$applyPlacement);
        };
 
        $typeahead.activate = function(index) {
          scope.$activeIndex = index;
        };
 
        $typeahead.select = function(index) {
          Iif(index === -1) return;
          var value = scope.$matches[index].value;
          // console.log('$setViewValue', value);
          controller.$setViewValue(value);
          controller.$render();
          scope.$resetMatches();
          if(parentScope) parentScope.$digest();
          // Emit event
          scope.$emit(options.prefixEvent + '.select', value, index, $typeahead);
        };
 
        // Protected methods
 
        $typeahead.$isVisible = function() {
          Iif(!options.minLength || !controller) {
            return !!scope.$matches.length;
          }
          // minLength support
          return scope.$matches.length && angular.isString(controller.$viewValue) && controller.$viewValue.length >= options.minLength;
        };
 
        $typeahead.$getIndex = function(value) {
          var l = scope.$matches.length, i = l;
          if(!l) return;
          for(i = l; i--;) {
            if(scope.$matches[i].value === value) break;
          }
          if(i < 0) return;
          return i;
        };
 
        $typeahead.$onMouseDown = function(evt) {
          // Prevent blur on mousedown
          evt.preventDefault();
          evt.stopPropagation();
        };
 
        $typeahead.$onKeyDown = function(evt) {
          if(!/(38|40|13)/.test(evt.keyCode)) return;
 
          // Let ngSubmit pass if the typeahead tip is hidden or no option is selected
          if($typeahead.$isVisible() && !(evt.keyCode === 13 && scope.$activeIndex === -1)) {
            evt.preventDefault();
            evt.stopPropagation();
          }
 
          // Select with enter
          if(evt.keyCode === 13 && scope.$matches.length) {
            $typeahead.select(scope.$activeIndex);
          }
 
          // Navigate with keyboard
          else if(evt.keyCode === 38 && scope.$activeIndex > 0) scope.$activeIndex--;
          else if(evt.keyCode === 40 && scope.$activeIndex < scope.$matches.length - 1) scope.$activeIndex++;
          else if(angular.isUndefined(scope.$activeIndex)) scope.$activeIndex = 0;
          scope.$digest();
        };
 
        // Overrides
 
        var show = $typeahead.show;
        $typeahead.show = function() {
          show();
          // use timeout to hookup the events to prevent
          // event bubbling from being processed imediately.
          $timeout(function() {
            $typeahead.$element.on('mousedown', $typeahead.$onMouseDown);
            Eif(options.keyboard) {
              element.on('keydown', $typeahead.$onKeyDown);
            }
          }, 0, false);
        };
 
        var hide = $typeahead.hide;
        $typeahead.hide = function() {
          $typeahead.$element.off('mousedown', $typeahead.$onMouseDown);
          Eif(options.keyboard) {
            element.off('keydown', $typeahead.$onKeyDown);
          }
          Eif(!options.autoSelect)
            $typeahead.activate(-1);
          hide();
        };
 
        return $typeahead;
 
      }
 
      TypeaheadFactory.defaults = defaults;
      return TypeaheadFactory;
 
    };
 
  })
 
  .directive('bsTypeahead', function($window, $parse, $q, $typeahead, $parseOptions) {
 
    var defaults = $typeahead.defaults;
 
    return {
      restrict: 'EAC',
      require: 'ngModel',
      link: function postLink(scope, element, attr, controller) {
 
        // Directive options
        var options = {scope: scope};
        angular.forEach(['placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'template', 'filter', 'limit', 'minLength', 'watchOptions', 'selectMode', 'autoSelect', 'comparator', 'id', 'prefixEvent', 'prefixClass'], function(key) {
          if(angular.isDefined(attr[key])) options[key] = attr[key];
        });
 
        // use string regex match boolean attr falsy values, leave truthy values be
        var falseValueRegExp = /^(false|0|)$/i;
        angular.forEach(['html', 'container', 'trimValue'], function(key) {
          if(angular.isDefined(attr[key]) && falseValueRegExp.test(attr[key])) options[key] = false;
        });
 
        // Disable browser autocompletion
        element.attr('autocomplete' ,'off');
 
        // Build proper bsOptions
        var filter = options.filter || defaults.filter;
        var limit = options.limit || defaults.limit;
        var comparator = options.comparator || defaults.comparator;
 
        var bsOptions = attr.bsOptions;
        Eif(filter) bsOptions += ' | ' + filter + ':$viewValue';
        if (comparator) bsOptions += ':' + comparator;
        Eif(limit) bsOptions += ' | limitTo:' + limit;
        var parsedOptions = $parseOptions(bsOptions);
 
        // Initialize typeahead
        var typeahead = $typeahead(element, controller, options);
 
        // Watch options on demand
        if(options.watchOptions) {
          // Watch bsOptions values before filtering for changes, drop function calls
          var watchedOptions = parsedOptions.$match[7].replace(/\|.+/, '').replace(/\(.*\)/g, '').trim();
          scope.$watchCollection(watchedOptions, function (newValue, oldValue) {
            // console.warn('scope.$watch(%s)', watchedOptions, newValue, oldValue);
            parsedOptions.valuesFn(scope, controller).then(function (values) {
              typeahead.update(values);
              controller.$render();
            });
          });
        }
 
        // Watch model for changes
        scope.$watch(attr.ngModel, function(newValue, oldValue) {
          // console.warn('$watch', element.attr('ng-model'), newValue);
          scope.$modelValue = newValue; // Publish modelValue on scope for custom templates
          parsedOptions.valuesFn(scope, controller)
          .then(function(values) {
            // Prevent input with no future prospect if selectMode is truthy
            // @TODO test selectMode
            Iif(options.selectMode && !values.length && newValue.length > 0) {
              controller.$setViewValue(controller.$viewValue.substring(0, controller.$viewValue.length - 1));
              return;
            }
            Iif(values.length > limit) values = values.slice(0, limit);
            var isVisible = typeahead.$isVisible();
            isVisible && typeahead.update(values);
            // Do not re-queue an update if a correct value has been selected
            if(values.length === 1 && values[0].value === newValue) return;
            !isVisible && typeahead.update(values);
            // Queue a new rendering that will leverage collection loading
            controller.$render();
          });
        });
 
        // modelValue -> $formatters -> viewValue
        controller.$formatters.push(function(modelValue) {
          // console.warn('$formatter("%s"): modelValue=%o (%o)', element.attr('ng-model'), modelValue, typeof modelValue);
          var displayValue = parsedOptions.displayValue(modelValue);
          return displayValue === undefined ? '' : displayValue;
        });
 
        // Model rendering in view
        controller.$render = function () {
          // console.warn('$render', element.attr('ng-model'), 'controller.$modelValue', typeof controller.$modelValue, controller.$modelValue, 'controller.$viewValue', typeof controller.$viewValue, controller.$viewValue);
          if(controller.$isEmpty(controller.$viewValue)) return element.val('');
          var index = typeahead.$getIndex(controller.$modelValue);
          var selected = angular.isDefined(index) ? typeahead.$scope.$matches[index].label : controller.$viewValue;
          selected = angular.isObject(selected) ? parsedOptions.displayValue(selected) : selected;
          var value = selected ? selected.toString().replace(/<(?:.|\n)*?>/gm, '') : '';
          element.val(options.trimValue === false ? value : value.trim());
        };
 
        // Garbage collection
        scope.$on('$destroy', function() {
          Eif (typeahead) typeahead.destroy();
          options = null;
          typeahead = null;
        });
 
      }
    };
 
  });